﻿using System;
using System.Text;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using Microsoft.Web.Hosting.Administration;

namespace SPForms.WebParts.ContactForm
{
    [ToolboxItemAttribute(false)]
    public partial class ContactForm : WebPart
    {
        public ContactForm()
        {
        }

        #region Properties
        #region Labels
        private string _Label_FullName = "Full name";
        [Personalizable(true)]
        [WebBrowsable(true)]
        [Category("Labels")]
        [WebDescription("Full name")]
        [WebDisplayName("Full name")]
        public string Label_FullName
        {
            get { return _Label_FullName; }
            set { _Label_FullName = value; }
        }

        private string _Label_eMail = "eMail";
        [Personalizable(true)]
        [WebBrowsable(true)]
        [Category("Labels")]
        [WebDescription("eMail")]
        [WebDisplayName("eMail")]
        public string Label_eMail
        {
            get { return _Label_eMail; }
            set { _Label_eMail = value; }
        }

        private string _Label_NotValidMailMessage = "Entered eMail is not valid";
        [Personalizable(true)]
        [WebBrowsable(true)]
        [Category("Labels")]
        [WebDescription("eMail not valid message")]
        [WebDisplayName("eMail not valid message")]
        public string Label_NotValidMailMessage
        {
            get { return _Label_NotValidMailMessage; }
            set { _Label_NotValidMailMessage = value; }
        }

        private string _Label_Content = "Content";
        [Personalizable(true)]
        [WebBrowsable(true)]
        [Category("Labels")]
        [WebDescription("Content")]
        [WebDisplayName("Content")]
        public string Label_Content
        {
            get { return _Label_Content; }
            set { _Label_Content = value; }
        }

        private string _Label_ButtonSubmit = "Submit";
        [Personalizable(true)]
        [WebBrowsable(true)]
        [Category("Labels")]
        [WebDescription("Submit")]
        [WebDisplayName("Submit")]
        public string Label_ButtonSubmit
        {
            get { return _Label_ButtonSubmit; }
            set { _Label_ButtonSubmit = value; }
        }

        private string _Label_ButtonCancel = "Cancel";
        [Personalizable(true)]
        [WebBrowsable(true)]
        [Category("Labels")]
        [WebDescription("Cancel")]
        [WebDisplayName("Cancel")]
        public string Label_ButtonCancel
        {
            get { return _Label_ButtonCancel; }
            set { _Label_ButtonCancel = value; }
        }

        private string _Label_CaptchaTryNew = "Can&#39;t read? Try different words.";
        [Personalizable(true)]
        [WebBrowsable(true)]
        [Category("Labels")]
        [WebDescription("CaptchaTryNew")]
        [WebDisplayName("CaptchaTryNew")]
        public string Label_CaptchaTryNew
        {
            get { return _Label_CaptchaTryNew; }
            set { _Label_CaptchaTryNew = value; }
        }

        #endregion
        #region Setup
        private string _Setup_MailAddress = "";
        [Personalizable(true)]
        [WebBrowsable(true)]
        [Category("Setup")]
        [WebDescription("eMail address")]
        [WebDisplayName("eMail address")]
        public string Setup_MailAddress
        {
            get { return _Setup_MailAddress; }
            set { _Setup_MailAddress = value; }
        }

        private string _Setup_MailSubject = "";
        [Personalizable(true)]
        [WebBrowsable(true)]
        [Category("Setup")]
        [WebDescription("eMail subject")]
        [WebDisplayName("eMail subject")]
        public string Setup_MailSubject
        {
            get { return _Setup_MailSubject; }
            set { _Setup_MailSubject = value; }
        }

        private string _Setup_MailContentTemplate = "<strong>Message info</strong></br>" +
                                                    "<strong>Full name:</strong> [FullName] </br>" +
                                                    "<strong>eMail:</strong> [eMail] </br>" +
                                                    "<strong>Content:</strong> [Content]";
        [Personalizable(true)]
        [WebBrowsable(true)]
        [Category("Setup")]
        [WebDescription("eMail content template")]
        [WebDisplayName("eMail content template")]
        public string Setup_MailContentTemplate
        {
            get { return _Setup_MailContentTemplate; }
            set { _Setup_MailContentTemplate = value; }
        }

        private string _Setup_SubmitUrl = "/";
        [Personalizable(true)]
        [WebBrowsable(true)]
        [Category("Setup")]
        [WebDescription("Submit url")]
        [WebDisplayName("Submit url")]
        public string Setup_SubmitUrl
        {
            get { return _Setup_SubmitUrl; }
            set { _Setup_SubmitUrl = value; }
        }

        private string _Setup_CancelUrl = "/";
        [Personalizable(true)]
        [WebBrowsable(true)]
        [Category("Setup")]
        [WebDescription("Cancel url")]
        [WebDisplayName("Cancel url")]
        public string Setup_CancelUrl
        {
            get { return _Setup_CancelUrl; }
            set { _Setup_CancelUrl = value; }
        }

        private bool _Setup_ShowMessageAfterSubmit = true;
        [Personalizable(true)]
        [WebBrowsable(true)]
        [Category("Setup")]
        [WebDescription("Show message after submit")]
        [WebDisplayName("Show message after submit")]
        public bool Setup_ShowMessageAfterSubmit
        {
            get { return _Setup_ShowMessageAfterSubmit; }
            set { _Setup_ShowMessageAfterSubmit = value; }
        }

        private string _Setup_AfterSumitMessage = "Mail sent";
        [Personalizable(true)]
        [WebBrowsable(true)]
        [Category("Setup")]
        [WebDescription("After submit message")]
        [WebDisplayName("After submit message")]
        public string Setup_AfterSumitMessage
        {
            get { return _Setup_AfterSumitMessage; }
            set { _Setup_AfterSumitMessage = value; }
        }

        public int MaxLetterCount { get; set; }

        
        
        #endregion
        #endregion

        #region PageEvents
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Microsoft.SharePoint.SPContext.Current.FormContext.FormMode == SPControlMode.Display) { pan_Main.Visible = true; }
            else if (Microsoft.SharePoint.SPContext.Current.FormContext.FormMode == SPControlMode.Edit) { pan_Main.Visible = false; }
            CssRegistration.Register("/_layouts/15/SPForms/design/css/main.css");
            if (!Page.IsPostBack)
            {
                this.SetLables();
                TryNew();
            }
        }
        #endregion

        #region ControlsEvents
        protected void lib_Send_Click(object sender, EventArgs e)
        {
            if (IsCaptchaValid)
            {
                string _MainContent = _Setup_MailContentTemplate;
                _MainContent = _MainContent.Replace("[FullName]", tb_FullName.Text);
                _MainContent = _MainContent.Replace("[eMail]", tb_eMail.Text);
                _MainContent = _MainContent.Replace("[Content]", tb_Content.Text);
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite _Site = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb _Web = _Site.OpenWeb(SPContext.Current.Web.ID))
                        {
                            SPUtility.SendEmail(_Web, false, false, _Setup_MailAddress, _Setup_MailSubject, _MainContent);
                        }
                    }
                });
                if (_Setup_ShowMessageAfterSubmit)
                {
                    lab_Message.Text = _Setup_AfterSumitMessage;
                }
                else
                {
                    Page.Response.Redirect(_Setup_SubmitUrl);
                }
                this.ClearInputs();
            }
            else
            {
                lab_Message.Text = "nije validirano";
            }
        }
        protected void lib_CaptchaTryNew_Click(object sender, EventArgs e)
        {
            TryNew();
        }
        #endregion

        #region Methods
        void SetLables()
        {
            lab_FullName.Text = _Label_FullName;
            lab_eMail.Text = _Label_eMail;
            lab_Content.Text = _Label_Content;
            lib_Send.Text = _Label_ButtonSubmit;
            hl_Cancel.Text = _Label_ButtonCancel;
            hl_Cancel.NavigateUrl = _Setup_CancelUrl;
            lib_CaptchaTryNew.Text = _Label_CaptchaTryNew;
            rev_eMail.Text = _Label_NotValidMailMessage;
        }
        void ClearInputs()
        {
            tb_FullName.Text = "";
            tb_eMail.Text = "";
            tb_Content.Text = "";
            tb_CaptchaTxt.Text = "";
        }
        public void TryNew()
        {
            char[] Valichars = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
            string Captcha = "";
            int LetterCount = MaxLetterCount > 5 ? MaxLetterCount : 5;
            for (int i = 0; i < LetterCount; i++)
            {
                char newChar = (char)0;
                do { newChar = Char.ToUpper(Valichars[new Random(DateTime.Now.Millisecond).Next(Valichars.Count() - 1)]); }
                while (Captcha.Contains(newChar));
                Captcha += newChar;
            }
            GeneratedText = Captcha;
            img_CaptchaImg.ImageUrl = "/_layouts/15/SPForms/captcha/GetImgText.aspx?CaptchaText=" + HttpUtility.UrlEncode(Convert.ToBase64String(SPForms.Common.Captcha.SecurityHelper.EncryptString(Captcha)));
        }
        public bool IsCaptchaValid
        {
            get
            {
                bool result = GeneratedText.ToUpper() == tb_CaptchaTxt.Text.Trim().ToUpper();
                if (!result) { TryNew(); }
                return result;
            }
        }
        private string GeneratedText
        {
            get
            {
                return ViewState[this.ClientID + "text"] != null ?
                    ViewState[this.ClientID + "text"].ToString() : null;
            }
            set
            {
                ViewState[this.ClientID + "text"] = value;
            }
        }
        #endregion
    }
}